class Category < ActiveRecord::Base
  has_many  :categorizations
  has_many  :vails, :through => :categorizations
  
  has_many  :attachments
  has_many  :datasheets, :through => :attachments
  
  has_one   :graphic, :as => :graphicable

	acts_as_versioned

  def to_param
    "#{id}-#{name.downcase.gsub(/[^[:alnum:]]/,'-')}".gsub(/-{2,}/,'-')   
  end
  
  def self.home_page
    self.find(:all, :conditions => ["home_page = ?", true])
  end
	
	# This method is used capture checkboxes for Datasheet and Category associated by a has_many :through => :attachments
	# See this link for a detailed discussion:
	# http://railsforum.com/viewtopic.php?id=803
	def datasheet_ids=(ids)
	  attachments.each do |attachment|
	    # Need to destroy the item that was not checked.
	    attachment.destroy unless ids.include? attachment.datasheet_id
	  end

	  ids.each do |ds_id|
	    self.attachments.create(:datasheet_id => ds_id) unless attachments.any? { |d| d.datasheet_id == ds_id }
	  end
	end 
end
